<?php
if (!defined('IN_IPB')) exit("<h1>Incorrect access</h1> You may not access this file without the acp.");

class converter extends template_plugin
{
	var $ipsclass;
	
	var $name = "Money Converter";
	var $multiple = 1;
	
	var $settings = array();
	
	function _load(&$plugin)
	{
		parent::_load($plugin);
		
		if($plugin['link'])
		{
			$this->settings = unserialize($plugin['plugin_config']);
		}
		else
		{
			$this->settings['field'] = 'points';
			$this->settings['field_name'] = 'Points';
			$this->settings['fee'] = 5;
			$this->settings['market_ratio'] = 1;
			$this->settings['other_ratio'] = 1;
			$this->settings['direction'] = 0;
		}
	}
	
	function acp_settings()
	{
		$fields = array();
		$field_dropdown = array();
		$no_fields = array('mgroup', 'joined', 'dst_in_use', 'allow_admin_mails','email_pm', 'email_full', 'skin', 'warn_level', 'warn_lastwarn', 'last_post', 'view_sigs', 'view_img', 'view_avs', 'view_pop', 'bday_day', 'bday_month', 'bday_year', 'new_msg', 'msg_total', 'show_popup', 'last_visit', 'last_activity', 'coppa_user', 'sub_end', 'member_login_key_expire', 'subs_pkg_chosen', 'has_blog', 'has_gallery', 'members_auto_dst', 'members_created_remote', 'members_disable_pm', 'failed_login_count', 'members_profile_views');
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'members'));
		$mem_fields = $this->ipsclass->DB->get_result_fields($this->ipsclass->DB->exec_query());
		foreach($mem_fields as $field)
		{
			if((isset($field->numeric) && !$field->numeric) || $field->unique_key || $field->primary_key || in_array($field->name,$no_fields))
			{
				continue;
			}
			
			if(strstr('time',$field->name) !== FALSE)
			{
				continue;
			}
			
			$fields[$field->name] = $field;
		}
		
		$this->ipsclass->DB->build_query_from_cache('get_full_fields',array('table'=>'members'),'sql_market_queries');
		$mem_fields = $this->ipsclass->DB->exec_query();
		while($field = $this->ipsclass->DB->fetch_row())
		{
			if(!isset($fields[$field['Field']]) || strstr($field['Type'],'tiny') !== FALSE || strstr($field['Type'],'small') !== FALSE || strstr($field['Type'],'medium') !== FALSE)
			{
				continue;
			}
			$field_dropdown[] = array($field['Field'],$field['Field']." [".$field['Type']."]");
		}

		
		$html = "";
		
		$html .= $this->ipsclass->adskin->add_td_row(array(
															"<b>What field in the ".SQL_PREFIX."members table in the database to convert this with?</b>",
															$this->ipsclass->adskin->form_dropdown('field',$field_dropdown,$this->settings['field']),
													)	);
		
		$html .= $this->ipsclass->adskin->add_td_row(array(
															"<b>What is name for this field?</b>",
															$this->ipsclass->adskin->form_input('field_name',$this->settings['field_name']),
													)	);
		
		$html .= $this->ipsclass->adskin->add_td_row(array(
															"<b>What is the percentage fee on the money being converted?</b><br />The fee is applied to the money being used in the market.",
															$this->ipsclass->adskin->form_simple_input('fee',$this->settings['fee'])."%",
													)	);
		
		$html .= $this->ipsclass->adskin->add_td_row(array(
															"<b>What is the ratio for the money being converted to ibMarket money?</b><br />For example if the ratio is 2:1, for every money used in ibMarket, it is 2 times the amount for the other money.",
															$this->ipsclass->adskin->form_simple_input('other_ratio',$this->settings['other_ratio']).":".$this->ipsclass->adskin->form_simple_input('market_ratio',$this->settings['market_ratio']),
													)	);
		
		$html .= $this->ipsclass->adskin->add_td_row(array(
															"<b>What is the direction of conversion?</b>",
															$this->ipsclass->adskin->form_dropdown('direction',array(array(0,'Allow the money to be converted in either direction'),array(1,'Only allow converting money from ibMarket to other'),array(2,'Only allow converting money from other to ibMarket')),$this->settings['direction']),
													)	);
		
		return $html;
	}
	
	function acp_save_settings(&$input)
	{
		$save = array();
		$save['field'] = $this->ipsclass->input['field'];
		$save['field_name'] = $this->ipsclass->input['field_name'];
		$save['fee'] = $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['fee']);
		$save['market_ratio'] = $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['market_ratio']);
		if($save['market_ratio'] == 0)
		{
			$this->ipsclass->admin->error("You cannot have a ratio of 0");
		}
		$save['other_ratio'] = $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['other_ratio']);
		if($save['other_ratio'] == 0)
		{
			$this->ipsclass->admin->error("You cannot have a ratio of 0");
		}
		$save['direction'] = min(max(intval($this->ipsclass->input['direction']),0),2);
		
		$input['plugin_config'] = serialize($save);
	}
	
	function acp_install()
	{
		$this->ipsclass->DB->load_cache_file(ROOT_PATH.'sources/market/sql/'.$this->ipsclass->vars['sql_driver'].'_plugin_queries.php','sql_plugin_queries');
		
		if($this->ipsclass->market_class->count_plugin_filename($this->plugin['filename']) == 0)
		{
			$this->ipsclass->DB->build_query_from_cache('table_converter_logs',array(),'sql_plugin_queries');
			$this->ipsclass->DB->exec_query();
		}
	}
	
	function acp_uninstall()
	{
		if($this->ipsclass->market_class->count_plugin_filename($this->plugin['filename']) == 1)
		{
			$this->ipsclass->DB->sql_drop_table( 'market_converter_logs' );
		}
	}
	
	function acp()
	{
		$LIMIT = 50;
		
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		
		$this->ipsclass->admin->page_title  = "Welcome to conversion log page";
		$this->ipsclass->admin->page_detail = "Welcome to conversion log page.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code, 'Conversion Logs' );
		
		$total = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_converter_logs','where'=>"l_link='".$this->plugin['link']."'"));
		$page = $this->ipsclass->adskin->build_pagelinks(	array(	'TOTAL_POSS'   => $total['total'],
																	'PER_PAGE'     => $LIMIT,
																	'USE_ST'       => 'st',
																	'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																	'L_SINGLE'     => "Single Page",
																	'BASE_URL'     => $this->ipsclass->base_url."&amp;".$this->ipsclass->form_code
															)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->html .= "<br />";
		
		$this->ipsclass->adskin->td_header[] = array( "When"       , "" );
		$this->ipsclass->adskin->td_header[] = array( "Member"     , "" );
		$this->ipsclass->adskin->td_header[] = array( "IP Address" , "" );
		$this->ipsclass->adskin->td_header[] = array( "Direction"  , "" );
		$this->ipsclass->adskin->td_header[] = array( "Amount"     , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Conversion Logs");
		
		$this->ipsclass->DB->build_query(array(
													'select' => 'l.*',
													'from' => array('market_converter_logs'=>'l'),
													'where' => "l_link='".$this->plugin['link']."'",
													'add_join' => array(
																			array(
																					'select' => 'm.members_display_name, m.mgroup',
																					'from' => array('members'=>'m'),
																					'where' => "m.id=l.l_member_id",
																					'type' => 'left',
																				),
																		),
													'order' => 'l_time DESC',
													'limit' => array($this->ipsclass->input['st'],$LIMIT)
										)		);
		$this->ipsclass->DB->exec_query();
		while($log = $this->ipsclass->DB->fetch_row())
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array(  $this->ipsclass->get_date($log['l_time'],'LONG'),
																				  $this->ipsclass->market_class->format_name($log['member_id'],$log['members_display_name'],$log['mgroup']),
																				  $log['l_ip_address'],
																				  ucfirst($log['l_direction'])." ibMarket Money",
																				  $this->ipsclass->do_number_format($log['l_amount']),
																		 )      );
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->admin->output();
	}
	
	function run()
	{
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->ipsclass->input['plugin']}'>".$this->plugin['name']."</a>");
		
		$this->ipsclass->load_template('skin_market_plugin');
		$this->ipsclass->load_language('lang_market_plugin');
		
		$this->settings['fee'] = $this->ipsclass->numbers->multiply($this->settings['fee'],$this->ipsclass->member['market_deduct']);
		
		if(in_array($this->ipsclass->member['mgroup'],$this->plugin['use_permission']) && $this->ipsclass->input['request_method'] == 'post')
		{
			$this->ipsclass->input['amount'] = $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['amount']);
			if($this->ipsclass->numbers->compare($this->ipsclass->input['amount'],0) < 0)
			{
				$this->ipsclass->Error(array('MSG'=>'convert_negative'));
			}
			
			$to = $this->settings['direction'];
			if($this->settings['direction'] == 0)
			{
				if($this->ipsclass->input['direction_to'] == 'market')
				{
					$to = 2;
				}
				elseif($this->ipsclass->input['direction_to'] == 'other')
				{
					$to = 1;
				}
				else
				{
					$this->ipsclass->Error(array('MSG'=>'invalid_error'));
				}
			}
			
			$ratio = 1;
			$market = 0;
			$other = 0;
			$fee = 0;
			if($to == 1)
			{
				$ratio = $this->ipsclass->numbers->divide($this->settings['other_ratio'],$this->settings['market_ratio']);
				$market = $this->ipsclass->numbers->subtract($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$this->ipsclass->input['amount']);
				$other = $this->ipsclass->numbers->add($this->ipsclass->member[$this->settings['field']],$this->ipsclass->numbers->multiply($this->ipsclass->input['amount'],$ratio));
				$fee = $this->ipsclass->numbers->multiply($this->ipsclass->input['amount'],$this->settings['fee'],.01);
			}
			elseif($to == 2)
			{
				$ratio = $this->ipsclass->numbers->divide($this->settings['market_ratio'],$this->settings['other_ratio']);
				$market = $this->ipsclass->numbers->add($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$this->ipsclass->numbers->multiply($this->ipsclass->input['amount'],$ratio));
				$other = $this->ipsclass->numbers->subtract($this->ipsclass->member[$this->settings['field']],$this->ipsclass->input['amount']);
				$fee = $this->ipsclass->numbers->multiply($this->ipsclass->input['amount'],$ratio,$this->settings['fee'],.01);
			}
			else
			{
				$this->ipsclass->Error(array('MSG'=>'invalid_error'));
			}
			
			$market = $this->ipsclass->numbers->round($market);
			$other = $this->ipsclass->numbers->round($other);
			$fee = $this->ipsclass->numbers->round($fee);
			$money = $this->ipsclass->numbers->subtract($market,$fee);
			
			if($this->ipsclass->numbers->compare($money,0) < 0)
			{
				$this->ipsclass->Error(array('MSG'=>'convert_negative'));
			}
			if($this->ipsclass->numbers->compare($other,0) < 0)
			{
				$this->ipsclass->Error(array('MSG'=>'convert_negative'));
			}
			
			$this->ipsclass->DB->do_update('members', array(
																$this->ipsclass->vars['market_members_field'] => $money,
																$this->settings['field']					  => $other,
						),"id=".$this->ipsclass->member['id']);
			
			$this->ipsclass->market_class->record_fee($fee);
			
			$this->ipsclass->DB->do_insert('market_converter_logs',array(
																			'l_link' => $this->ipsclass->input['plugin'],
																			'l_member_id' => $this->ipsclass->member['id'],
																			'l_ip_address' => $this->ipsclass->ip_address,
																			'l_time' => time(),
																			'l_direction' => $to == 1 ? 'from' : 'to',
																			'l_amount' => $this->ipsclass->input['amount'],
																			'l_fee' => $fee,
											)							);
			
			$this->ipsclass->market_class->redirect('convert_money_converted',"plugin=".$this->ipsclass->input['plugin']);
		}
		else
		{
			$this->ipsclass->lang['convert_to_other'] = str_replace("<#FROM#>",$this->ipsclass->vars['market_currency'],$this->ipsclass->lang['convert_to_x']);
			$this->ipsclass->lang['convert_to_other'] = str_replace("<#TO#>",$this->settings['field_name'],$this->ipsclass->lang['convert_to_other']);
			$this->ipsclass->lang['convert_to_market'] = str_replace("<#TO#>",$this->ipsclass->vars['market_currency'],$this->ipsclass->lang['convert_to_x']);
			$this->ipsclass->lang['convert_to_market'] = str_replace("<#FROM#>",$this->settings['field_name'],$this->ipsclass->lang['convert_to_market']);
			
			$this->ipsclass->member['other_money'] = $this->ipsclass->do_number_format($this->ipsclass->member[$this->settings['field']]);
			
			$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->covert_form($this->settings);
		}
	}
}
?>